package com.planet.merchant.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.planet.common.exception.ServiceException;
import com.planet.common.utils.StringUtils;
import com.planet.common.utils.bean.BeanValidators;
import com.planet.merchant.domain.PmsProductCode;
import com.planet.merchant.domain.vo.ProductCodeBindVo;
import com.planet.merchant.mapper.PmsProductCodeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.planet.merchant.mapper.PmsProductCodeBindMapper;
import com.planet.merchant.domain.PmsProductCodeBind;
import com.planet.merchant.service.IPmsProductCodeBindService;

/**
 * 二维码绑定关系Service业务层处理
 *
 * @author ggm
 * @date 2025-03-29
 */
@Service
public class PmsProductCodeBindServiceImpl extends ServiceImpl<PmsProductCodeBindMapper, PmsProductCodeBind> implements IPmsProductCodeBindService {
    @Autowired
    private PmsProductCodeBindMapper pmsProductCodeBindMapper;
    @Autowired
    private PmsProductCodeMapper pmsProductCodeMapper;

    /**
     * 查询二维码绑定关系
     *
     * @param id 二维码绑定关系主键
     * @return 二维码绑定关系
     */
    @Override
    public PmsProductCodeBind selectPmsProductCodeBindById(Long id) {
        return pmsProductCodeBindMapper.selectPmsProductCodeBindById(id);
    }

    /**
     * 查询二维码绑定关系列表
     *
     * @param pmsProductCodeBind 二维码绑定关系
     * @return 二维码绑定关系
     */
    @Override
    public List<PmsProductCodeBind> selectPmsProductCodeBindList(PmsProductCodeBind pmsProductCodeBind) {
        return pmsProductCodeBindMapper.selectPmsProductCodeBindList(pmsProductCodeBind);
    }

    /**
     * 新增二维码绑定关系
     *
     * @param pmsProductCodeBind 二维码绑定关系
     * @return 结果
     */
    @Override
    public int insertPmsProductCodeBind(PmsProductCodeBind pmsProductCodeBind) {
        pmsProductCodeBind.setStatus(0);
        return pmsProductCodeBindMapper.insertPmsProductCodeBind(pmsProductCodeBind);
    }

    /**
     * 修改二维码绑定关系
     *
     * @param pmsProductCodeBind 二维码绑定关系
     * @return 结果
     */
    @Override
    public int updatePmsProductCodeBind(PmsProductCodeBind pmsProductCodeBind) {
        return pmsProductCodeBindMapper.updatePmsProductCodeBind(pmsProductCodeBind);
    }

    /**
     * 批量删除二维码绑定关系
     *
     * @param ids 需要删除的二维码绑定关系主键
     * @return 结果
     */
    @Override
    public int deletePmsProductCodeBindByIds(Long[] ids) {
        return pmsProductCodeBindMapper.deletePmsProductCodeBindByIds(ids);
    }

    /**
     * 删除二维码绑定关系信息
     *
     * @param id 二维码绑定关系主键
     * @return 结果
     */
    @Override
    public int deletePmsProductCodeBindById(Long id) {
        return pmsProductCodeBindMapper.deletePmsProductCodeBindById(id);
    }

    @Override
    public List<ProductCodeBindVo> selectPmsProductCodeBindTree() {
        QueryWrapper<PmsProductCodeBind> qw = new QueryWrapper<>();
        List<PmsProductCodeBind> pmsProductCodeBinds = pmsProductCodeBindMapper.selectList(qw);

        // 按照Level3Code分组
        Map<String, List<PmsProductCodeBind>> map = pmsProductCodeBinds.stream()
                .filter(pmsProductCodeBind -> pmsProductCodeBind.getLevel3Code() != null)
                .collect(Collectors.groupingBy(PmsProductCodeBind::getLevel3Code));

        // 创建结果列表，用于存储所有父节点
        List<ProductCodeBindVo> result = new ArrayList<>();

        // 遍历分组，构造树形结构
        for (Map.Entry<String, List<PmsProductCodeBind>> entry : map.entrySet()) {
            String level3code = entry.getKey();
            ProductCodeBindVo parent = new ProductCodeBindVo();
            QueryWrapper<PmsProductCode> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("code", level3code);
            PmsProductCode productCode = pmsProductCodeMapper.selectOne(queryWrapper);
            if(productCode!=null){
                parent.setId(productCode.getId());
            }
            parent.setLevel3Code(level3code);
            parent.setLabel("箱码：" + level3code + (entry.getValue().get(0).getStatus() == 0 ? "未入库" : "已入库"));
            parent.setChildren(new ArrayList<>()); // 初始化父节点的子节点列表

            // 构造子节点
            List<ProductCodeBindVo> children = entry.getValue().stream()
                    .map(bind -> {
                        ProductCodeBindVo child = new ProductCodeBindVo();
                        String level1Code = bind.getLevel1Code();
                        String label = "盒码:" + bind.getLevel2Code() + (bind.getStatus() == 0 ? "未入库" : "已入库");
                        if (level1Code != null && !level1Code.isEmpty()) {
                            label += "，瓶码：" + level1Code + (bind.getStatus() == 0 ? "未入库" : "已入库");
                            child.setLevel1Code(level1Code);
                        }
                        child.setLevel3Code(bind.getLevel3Code());
                        child.setId(bind.getId());
                        child.setLabel(label);
                        child.setLevel2Code(bind.getLevel2Code());
                        child.setChildren(new ArrayList<>()); // 初始化子节点的子节点列表
                        return child;
                    })
                    .collect(Collectors.toCollection(ArrayList::new));

            // 将子节点添加到父节点
            parent.getChildren().addAll(children);

            // 将父节点添加到结果列表
            result.add(parent);
        }
        // 返回所有父节点的列表
        return result;
    }

    @Override
    public int deletePmsProductCodeBindByLeve3Code(String level3code) {
        QueryWrapper<PmsProductCodeBind> qw = new QueryWrapper<>();
        qw.eq("level3_code", level3code);
        List<PmsProductCodeBind> pmsProductCodeBinds = pmsProductCodeBindMapper.selectList(qw);
        Set<Long> Ids = pmsProductCodeBinds.stream().map(it -> it.getId()).collect(Collectors.toSet());
        Long[] idsArray = Ids.toArray(new Long[0]);
        return pmsProductCodeBindMapper.deletePmsProductCodeBindByIds(idsArray);
    }

    @Override
    public int updateBindByLevel3code(String level3code, String newLevel3code) {
        QueryWrapper<PmsProductCodeBind> qw = new QueryWrapper<>();
        qw.eq("level3_code", level3code);
        List<PmsProductCodeBind> pmsProductCodeBinds = pmsProductCodeBindMapper.selectList(qw);
        if (pmsProductCodeBinds.size() > 0) {
            List<PmsProductCodeBind> collect = pmsProductCodeBinds.stream().map(it -> {
                it.setLevel3Code(newLevel3code);
                return it;
            }).collect(Collectors.toList());
            for (PmsProductCodeBind productCodeBind : collect) {
                pmsProductCodeBindMapper.updatePmsProductCodeBind(productCodeBind);
            }
        }
        return 1;
    }

    @Override
    public int storeById(Long id) {
        PmsProductCodeBind pmsProductCodeBind = pmsProductCodeBindMapper.selectById(id);
        //先判断二维码等级
        PmsProductCode pmsProductCode = pmsProductCodeMapper.selectPmsProductCodeById(id);
        if(pmsProductCode!=null){
           if(pmsProductCode.getLevel()==3){
               //获取所有的一级二级二维码并修改他们的入库状态
               QueryWrapper<PmsProductCodeBind> queryWrapper = new QueryWrapper<>();
               queryWrapper.eq("level3_code",pmsProductCode.getCode());
               List<PmsProductCodeBind> pmsProductCodeBinds = pmsProductCodeBindMapper.selectList(queryWrapper);
               pmsProductCodeBinds.stream().forEach(it -> {
                   it.setStatus(1);
                   pmsProductCodeBindMapper.updateById(it);
               });
           }
        }else {
            if (pmsProductCodeBind.getStatus() == 1) {
                throw new ServiceException("该二维码已入库，请勿重复入库！");
            } else {
                pmsProductCodeBind.setStatus(1);
            }
            pmsProductCodeBindMapper.updateById(pmsProductCodeBind);
        }
        return 1;
    }

    @Override
    public int storeByLevel3Code(String level3code) {
        QueryWrapper<PmsProductCodeBind> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("level3_code", level3code);
        List<PmsProductCodeBind> pmsProductCodeBinds = pmsProductCodeBindMapper.selectList(queryWrapper);
        pmsProductCodeBinds.stream().forEach(it -> {
            it.setStatus(1);
            pmsProductCodeBindMapper.updateById(it);
        });
        return 1;
    }

    @Override
    public String importUser(List<PmsProductCodeBind> productCodeBindList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(productCodeBindList) || productCodeBindList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (PmsProductCodeBind pmsProductCodeBind : productCodeBindList) {
            try {
                //BeanValidators.validateWithException(validator, pmsProductCodeBind);
                this.insertPmsProductCodeBind(pmsProductCodeBind);
                successNum++;
                successMsg.append("<br/>" + successNum + "、账号 " + pmsProductCodeBind.getLevel1Code() + " 导入成功");

            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + pmsProductCodeBind.getLevel1Code() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


}
